<script lang="ts" setup>
import { differenceInDays, differenceInHours, differenceInMinutes, differenceInSeconds } from 'date-fns';
import dayjs from 'dayjs';
const urlHome = useUrl();

interface OrdersSchema {
  id: number
  document_date: Date
  incoming_weight: number
  outgoing_weight: number
  incoming_document: string
}

const props = defineProps<{
  contract_id?: number,
  stock_code: string,
  product_id?: number,
  ordersList?: OrdersSchema[] | null,
  balance?: number,
  ordersListRefresh: Function,
  contractProductRefresh: Function,
}>()
const balance = ref(props.balance);
const username = useCookie('username');

const priceStock = computed(() => props.balance && props.ordersList ? props.balance + props.ordersList?.reduce((acc, value) => Number(acc) + Number(value.incoming_weight), 0) : 0);

async function deleteDocument(document_id: number) {
  const response = await $fetch(`${urlHome.value}orders/delete_stock/`, {
    method: 'DELETE',
    body: {
      username: username.value,
      document_id: document_id,
    }
  });
  if (response) {
    console.log("success delete");
    props.ordersListRefresh();
    props.contractProductRefresh();
    // await rerenderRun();
  }
}

watchEffect(() => {
  balance.value = props.balance;
  props.ordersList?.reduce((acc, value) => acc + value.incoming_weight, 0)
})

</script>
<template>
  <table id="lgottable" class="text-center">
    <thead class="sticky-header">
      <tr>
        <th>№п/п</th>
        <th>Дата</th>
        <th>Документ</th>
        <th>Расход</th>
        <th>Удалить</th>
      </tr>
    </thead>
    <tbody>
      <template
        v-for="( item, index ) in props.ordersList?.sort((a, b) => differenceInDays(new Date(a.id), new Date(b.id)))"
        v-auto-animate :key="item.id" class="flex gap-2 text-right font-mono place-content-evenly">
        <tr>
          <td>{{ index + 1 }}</td>
          <td>{{ item.document_date ? dayjs(item.document_date).format('DD.MM.YYYY') : "" }}</td>
          <td>{{ item.id }}</td>
          <td>{{ item.outgoing_weight }}</td>
          <td>
            <UButton icon="i-heroicons-trash" color="gray" @click="deleteDocument(item.id)" />
          </td>
        </tr>
      </template>
    </tbody>
  </table>
</template>
<style scoped>
#lgottable {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#lgottable td,
#lgottable th {
  border: 1px solid #ddd;
  padding: 8px;
}

#lgottable tr:nth-child(even) {
  background-color: #f2f2f2;
}

#lgottable tr:hover {
  background-color: #ddd;
}

#lgottable th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: center;
  background-color: #04AA6D;
  color: white;
}

.sticky-header {
  position: sticky;
  top: 0;
  background-color: white;
  /* или другой цвет фона */
  z-index: 49;
  /* чтобы обеспечить, что элемент находится над другими */
}
</style>